package cn.edu.sdjzu.xg23.kcsj01_backend.service.impl;


import cn.edu.sdjzu.xg23.kcsj01_backend.entity.Patent;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Permission;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.Role;
import cn.edu.sdjzu.xg23.kcsj01_backend.entity.authority.RoleAssPermission;
import cn.edu.sdjzu.xg23.kcsj01_backend.mapper.RoleMapper;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> selectRolesByCondition(Integer pageNum, Integer pageSize, Role role) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> patentList = roleMapper.selectRolesByCondition(role);
        return new PageInfo<>(patentList);
    }

    @Override
    public List<Role> selectRolesByUserId(Long id) {
        return roleMapper.selectRolesByUserId(id);
    }

    @Override
    @Transactional
    public boolean insertRole(Role role) {
        // 1. 插入角色基本信息
        boolean insertResult = roleMapper.insertRole(role);
        if (insertResult && role.getPermissions() != null) {
            // 2. 分配权限（保存角色-权限关联）
            roleMapper.insertRolePermissions(role.getId(), role.getPermissions());
        }
        return insertResult;
    }

    @Override
    @Transactional
    public boolean updateRole(Role role) {
        // 1. 更新角色基本信息
        boolean updateResult = roleMapper.updateRole(role);
        if (updateResult && role.getPermissions() != null) {
            // 2. 先删除原有权限，再分配新权限
            roleMapper.deleteRolePermissions(role.getId());
            roleMapper.insertRolePermissions(role.getId(), role.getPermissions());
        }
        return updateResult;
    }

    @Override
    @Transactional
    public boolean deleteRoleById(Long id) {
        try {
            return roleMapper.deleteRoleById(id);
        } catch (Exception e) {
            logger.error("删除角色失败，角色ID：{}", id, e);
            return false;
        }
    }

    @Override
    public List<Permission> selectPermissionsByRoleId(Long roleId) {
        return roleMapper.selectPermissionsByRoleId(roleId);
    }



}